package com.gorkr.labuladong.data_struct.array;

import org.junit.jupiter.api.Test;

import java.util.HashMap;

public class E39ShuZuZhongChuXianCiShuChaoGuoYiBanDeShuZiIcof {

    public int majorityElement(int[] nums) {
        int length = nums.length;
        int half = length / 2;

        // 数字 - 次数
        HashMap<Integer, Integer> map = new HashMap<>();

        for (int num :
                nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
            if (map.get(num) > half) {
                return num;
            }
        }
        return Integer.MAX_VALUE;
    }

    // 投票算法
    public int majorityElement2(int[] nums) {
        int res = 0, voted = 0;

        for (int num :
                nums) {
            if (voted == 0) {
                res = num;
            }
            voted += res == num ? 1 : -1;
        }
        return res;

    }


    @Test
    public void test() {
        int[] nums = {1, 2, 3, 2, 2, 2, 5, 4, 2};
        System.out.println(majorityElement2(nums));

    }


}
